import React from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableHighlight,
  TouchableOpacity,
  Dimensions,
  Platform,
  DimensionValue,
} from "react-native";
import Modal from "react-native-modal";
import { BottomSheetProps } from "./types";
import { useTheme } from "@/contexts/ThemeContext";

const { width, height } = Dimensions.get("window");

/**
 * 底部弹出面板组件
 *
 * 模仿微信风格的底部弹出菜单，可包含多个选项
 * @author BelovedLYC
 */
const BottomSheet: React.FC<BottomSheetProps> = ({
  visible,
  onClose,
  title,
  subtitle,
  children,
  content,
  cancelText = "取消",
  onCancel,
  closeOnTouchOutside = true,
  height: customHeight,
  containerStyle,
  contentStyle,
  titleStyle,
  subtitleStyle,
  cancelButtonStyle,
  cancelTextStyle,
  animationDuration = 300,
  backdropColor = "rgba(0, 0, 0, 0.4)",
  borderRadius = 10,
  hideCancel = false,
  showMultiSelect = false,
  multiSelectText = "多选",
  onMultiSelect,
  multiSelectStyle,
  showTitleCancel = true,
  titleCancelText = "取消",
  onTitleCancel,
  titleCancelStyle,
}) => {
  const { colors } = useTheme();

  // 处理取消按钮点击
  const handleCancel = () => {
    if (onCancel) {
      onCancel();
    } else {
      onClose();
    }
  };

  // 处理标题栏取消按钮点击
  const handleTitleCancel = () => {
    if (onTitleCancel) {
      onTitleCancel();
    } else {
      onClose();
    }
  };

  // 处理多选按钮点击
  const handleMultiSelect = () => {
    if (onMultiSelect) {
      onMultiSelect();
    }
  };

  // 处理背景点击
  const handleBackdropPress = () => {
    if (closeOnTouchOutside) {
      onClose();
    }
  };

  // 计算容器高度，默认为整个屏幕高度
  const containerHeight: DimensionValue =
    customHeight || (content && hideCancel ? "100%" : "100%");

  return (
    <Modal
      isVisible={visible}
      onBackdropPress={handleBackdropPress}
      onBackButtonPress={onClose}
      backdropColor={backdropColor}
      backdropOpacity={1}
      animationIn="slideInUp"
      animationOut="slideOutDown"
      animationInTiming={animationDuration}
      animationOutTiming={animationDuration}
      useNativeDriverForBackdrop
      useNativeDriver
      statusBarTranslucent
      style={styles.modal}
    >
      <View
        style={[
          styles.container,
          {
            backgroundColor: colors.background,
            borderTopLeftRadius: borderRadius,
            borderTopRightRadius: borderRadius,
            height: containerHeight,
          },
          containerStyle,
        ]}
      >
        {/* 标题栏区域，包含多选和取消按钮 */}
        <View
          style={[
            styles.titleBar,
            {
              borderBottomColor: colors.border.divider,
            },
          ]}
        >
          {/* 左侧多选按钮 */}
          <View style={styles.titleLeftAction}>
            {showMultiSelect && (
              <TouchableOpacity onPress={handleMultiSelect}>
                <Text
                  style={[
                    styles.actionText,
                    { color: colors.primary },
                    multiSelectStyle,
                  ]}
                >
                  {multiSelectText}
                </Text>
              </TouchableOpacity>
            )}
          </View>

          {/* 中间标题 */}
          <View style={styles.titleCenter}>
            {title && (
              <Text
                style={[
                  styles.title,
                  { color: colors.text.primary },
                  titleStyle,
                ]}
                numberOfLines={1}
              >
                {title}
              </Text>
            )}
          </View>

          {/* 右侧取消按钮 */}
          <View style={styles.titleRightAction}>
            {showTitleCancel && (
              <TouchableOpacity onPress={handleTitleCancel}>
                <Text
                  style={[
                    styles.actionText,
                    { color: colors.text.primary },
                    titleCancelStyle,
                  ]}
                >
                  {titleCancelText}
                </Text>
              </TouchableOpacity>
            )}
          </View>
        </View>

        {/* 子标题区域 */}
        {subtitle && (
          <Text
            style={[
              styles.subtitle,
              { color: colors.text.secondary },
              subtitleStyle,
            ]}
          >
            {subtitle}
          </Text>
        )}

        {/* 内容区域 - 根据是否有content属性决定渲染方式 */}
        <View
          style={[
            styles.content,
            // 当使用content属性且hideCancel为true时，给内容区域设置较高的高度
            content && hideCancel ? { flex: 1 } : {},
            contentStyle,
          ]}
        >
          {content || children}
        </View>

        {/* 只有不隐藏取消按钮时才显示间隔线和取消按钮 */}
        {!hideCancel && (
          <>
            {/* 取消按钮 */}
            <TouchableHighlight
              underlayColor={colors.border.divider}
              onPress={handleCancel}
              style={[styles.cancelButton, cancelButtonStyle]}
            >
              <Text
                style={[
                  styles.cancelText,
                  { color: colors.text.primary },
                  cancelTextStyle,
                ]}
              >
                {cancelText}
              </Text>
            </TouchableHighlight>
          </>
        )}
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  modal: {
    margin: 0,
    justifyContent: "flex-end",
  },
  container: {
    width: width,
    overflow: "hidden",
    paddingBottom: Platform.OS === "ios" ? 34 : 16, // 适配底部安全区域
    maxHeight: height * 0.9, // 最大占屏幕高度的90%
  },
  titleBar: {
    flexDirection: "row",
    paddingHorizontal: 16,
    paddingVertical: 12,
    alignItems: "center",
    justifyContent: "space-between",
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  titleLeftAction: {
    flex: 1,
    alignItems: "flex-start",
  },
  titleCenter: {
    flex: 2,
    alignItems: "center",
  },
  titleRightAction: {
    flex: 1,
    alignItems: "flex-end",
  },
  actionText: {
    fontSize: 16,
    fontWeight: "500",
    ...Platform.select({
      ios: {
        fontFamily: "System",
      },
      android: {
        fontFamily: "sans-serif-medium",
      },
    }),
  },
  title: {
    fontSize: 18,
    fontWeight: "600",
    textAlign: "center",
    ...Platform.select({
      ios: {
        fontFamily: "System",
      },
      android: {
        fontFamily: "sans-serif-medium",
      },
    }),
  },
  subtitle: {
    fontSize: 14,
    textAlign: "center",
    paddingHorizontal: 16,
    paddingTop: 8,
    paddingBottom: 12,
    ...Platform.select({
      ios: {
        fontFamily: "System",
      },
      android: {
        fontFamily: "sans-serif",
      },
    }),
  },
  content: {
    flexGrow: 1, // 内容区域可伸缩
  },
  separator: {
    height: 8,
    width: "100%",
  },
  cancelButton: {
    width: "100%",
    paddingVertical: 16,
    alignItems: "center",
    justifyContent: "center",
  },
  cancelText: {
    fontSize: 17,
    fontWeight: "600",
    ...Platform.select({
      ios: {
        fontFamily: "System",
      },
      android: {
        fontFamily: "sans-serif-medium",
      },
    }),
  },
});

export default BottomSheet;
